<?php

/**
 * 友情链接模型
 */
if ( !defined( 'BASEPATH' ) ) exit( 'No direct script access allowed' );

class Link_model extends MY_Model
{

    public $_table = array(
        'link' => 'link',
    );
    public $_fields = array(
        'link' => array(
            'id' => 'id',
            'name' => 'name',
            'url' => 'url',
            'addtime' => 'addtime',
            'visible' => 'visible',
        ),
    );

    /**
     * 获取全部友情链接
     * @param int $offset 游标
     * @param int $limit 显示条数
     * @return array
     */
    public function getAll( $offset = 0, $limit = 0 )
    {
        return $this->db->select( 'id,name,url,visible' )
                        ->from( $this->_table['link'] )
                        ->get()
                        ->result_array();
    }

    /**
     * 根据链接ID获取数据
     * @param int $linkId 链接ID
     * @return array 
     */
    public function getById( $linkId )
    {
        return $this->db->select( 'id,name,url,visible' )
                        ->from( $this->_table['link'] )
                        ->where( 'id', $linkId )
                        ->get()
                        ->row_array();
    }

    public function getDataByName( $linkName )
    {
        return $this->db->select( 'id,name,url,visible' )
                        ->from( $this->_table['link'] )
                        ->where( 'name', $linkName )
                        ->get()
                        ->row_array();
    }
    
    /**
     * 添加友情链接
     * @param array $data 数据
     * @return int 链接ID 
     */
    public function add( $data )
    {
        $insertData = array(
            'name' => $data['name'],
            'url' => $data['url'],
            'visible' => isset( $data['visible'] ) ? intval( $data['visible'] ) : 0,
        );
        $this->db->insert( $this->_table['link'], $insertData );
        return $this->db->insert_id();
    }
    
    public function updateById( $data, $linkId )
    {
        $updateData = array(
            'name' => $data['name'],
            'url' => $data['url'],
            'visible' => isset( $data['visible'] ) ? intval( $data['visible'] ) : 0,
        );
        $this->db->update( $this->_table['link'], $updateData );
        return $this->db->affected_rows();
    }
    
    public function deleteById( $linkId )
    {
        $this->db->where('id', $linkId)->delete( $this->_table['link'] );
        return $this->db->affected_rows();
    }
    
}

?>
